package com.ynny.bookmanagersystem.controller;

import com.ynny.bookmanagersystem.dao.UserDao;
import com.ynny.bookmanagersystem.dao.UserDaoImpl;
import com.ynny.bookmanagersystem.entity.User;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/user/addUser")
public class AddUserServlet extends HttpServlet {


    @Override
    protected void service(HttpServletRequest request,
                           HttpServletResponse response) throws ServletException, IOException {

        String userName = request.getParameter("username");

        String pwd = request.getParameter("pwd");

        String name = request.getParameter("name");

        String age = request.getParameter("age");


        UserDao userDao = new UserDaoImpl();


        User user = new User();
        user.setUserName(userName);
        user.setPassword(pwd);
        user.setName(name);
        user.setAge(Integer.parseInt(age));

        int i = userDao.insertUser(user);

        if (i > 0){
            List<User> users = userDao.selectAllUsers();

            request.getSession().setAttribute("users", users);
            response.sendRedirect( request.getContextPath() +
                    "/user/list.jsp");
        }


    }
}
